<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        canvas {
            display: block;
            border: 1px solid yellowgreen;
        }
    </style>
</head>

<body>
    <!-- 
        canvas:双闭合标签 
        --默认宽度与高度：300 * 150
        --鼠标右边，浏览器认为他是一张图片，可以保存！！！

        注意事项1:给canvas标签添加文本|添加子节点没有任何意义
        你想操作canvas必须通过JS操作
        注意事项2:canvas类似img标签，它的宽度与高度必须通过属性width|height设置
        不能通过样式设置
    -->
    <canvas width="600" height="400"></canvas>
</body>

</html>
<script>
    //获取canvas标签
    let canvas = document.querySelector('canvas');
    //想在canvas画布上绘制图形、图标---JS[画笔] 对象:属性|方法用来操作canvas画布
    //canvas.getContext传递参数2D
    let ctx = canvas.getContext('2d');

    //线段的颜色
    //线段w
    ctx.lineWidth = 3;
    ctx.strokeStyle = 'red';

    //给canvas绑定事件
    canvas.onmousedown = function (event) {
        //鼠标按钮的时候：设置线段起点
        ctx.moveTo(event.clientX, event.clientY);
        //鼠标移动
        canvas.onmousemove = function (event) {
            ctx.lineTo(event.clientX, event.clientY);
            //绘制出线段
            ctx.stroke();
        }
    }
    canvas.onmouseup = function(){
        //清除鼠标移动事件
        canvas.onmousemove = null;
    }
</script>